package com.lgj.springboot_lgj.web.inetrceotor;

import com.lgj.springboot_lgj.exception.CustomerException;
import com.lgj.springboot_lgj.utils.JwtUtil;
import com.lgj.springboot_lgj.utils.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @Author:Lijun
 * @Date:2022/6/15
 */
@Slf4j
@Component
@RestControllerAdvice
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    //开始之前拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("在调用controller开始拦截");
        /*
        * 通过请求头获取用户提交的token
        * */
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            return true;
        }
        String token;
         token = request.getHeader("Authorization");
         if(token==null){
            token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjo2MTY1NTcwODg4NCwiaW5mbyI6eyJyb2xlIjowLCJ1c2VybmFtZSI6ImFkbWluIiwicmVhbG5hbWUiOiLliJjkuprok4kifX0.OT5AAntk4sdnyseXV2P48vq9oYZ2L0xLZrMReUWzmMk";
        }
        /*
         * 通过请求头获取用户提交的token
         * */
        if(token==null){
            throw new CustomerException("请登录后在在执行");
        }
        //提供了Token进行效验是否有效
        try{
            JwtUtil.checkSign(token);
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomerException("token无效请重新登录！");
        }
        //根据token字符串获取用户基本信息
        Map<String, Object> userInfo = JwtUtil.getInfo(token);
        System.out.println("-------你好，这是一个拦截器测试！");
        //将userInfo 能在service层的方法中获取到
        //请求方法
        userInfo.put("url",request.getRequestURI());
        userInfo.put("method",request.getMethod());
        //将userInfo能在service层的方法中获取到
        UserInfoUtil.setUserInfo(userInfo);
        //将userInfo能在service层的方法中获取到
        return true;//默认允许拦截
    }
    @Override
    //执行方法后拦截
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("controller"+request.getMethod()+"执行结束后拦截....");
    }

    @Override
    //最后结束执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("view和model组合结束后执行");
        log.info("最后执行时间："+new Date());
    }
}
